import 'package:flutter/material.dart';
import 'package:get/get.dart';

class AnimateList extends StatefulWidget {
  const AnimateList({ Key? key }) : super(key: key);
  @override
  _AnimateListState createState() => _AnimateListState();
}

class _AnimateListState extends State<AnimateList> {
   var  data = <String>[] ;
    int counter = 5;
    final globalKey = GlobalKey<AnimatedListState>();
  @override
  Widget build(BuildContext context) {
   
    @override
    void initState(){
      for(var i =0;i<counter;i++){
        data.add('${i+1}');
      }
      super.initState();
    }
    return Scaffold(
      appBar: AppBar(
        title:Text('animatList'),
      ),
      body: Stack(
        children: [
          AnimatedList(
            key:globalKey,
            initialItemCount:data.length,
            itemBuilder:(BuildContext context,int index,Animation<double> animation){
              return FadeTransition(opacity: animation,child: buildItem(context,index));
            } ,
          ),
          buildAddBtn()
        ],
      ),
    );
  }
 
  Widget buildAddBtn() {
    return Positioned(child: FloatingActionButton(
      child: const Icon(Icons.add),
      onPressed: (){
        data.add('${++counter}');
        globalKey.currentState!.insertItem(data.length-1);
        print('添加 $counter');
      },
    ));
  }
  
  Widget buildItem(context, index) {
    String char = data[index];
    return ListTile(
      key:ValueKey(char),
      title:Text(char),
      trailing: IconButton(
        icon:const Icon(Icons.delete),
        onPressed: () => onDelete(context, index),
      ),
    );
  }
  
  void onDelete(context,index) {
    setState(() {
      globalKey.currentState!.removeItem(index, (context, animation){
        var item = buildItem(context, index);
        data.removeAt(index);
        return FadeTransition(opacity: CurvedAnimation(
          parent: animation,
          curve: const Interval(0.5,1.0)
        ),
        child: SizeTransition(
          sizeFactor: animation,
          axisAlignment: 0.0,
          child: item,
        ),);
      },duration: const Duration(milliseconds: 200));
    });
  }
}